﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace Galaxy.Libra.DapperExtensions.DBBuilder.MySQL
{
    public class MySQLDBQueryer: IDataBaseQueryer
    {
        protected IDbConnection curDbConnection = null;

        public MySQLDBQueryer(IDbConnection dbConnection)
        {
            curDbConnection = dbConnection;
        }

        public IEnumerable<string> ShowDataBases()
        {
            string sql = "SHOW DATABASES;";
            IEnumerable<string> result = new List<string>();

            if (curDbConnection != null)
            {
                using (curDbConnection)
                {
                    if (curDbConnection.State != ConnectionState.Open)
                        curDbConnection.Open();

                    result = curDbConnection.Query<string>(sql);

                    curDbConnection.Close();
                }
            }
            return result;
        }

        public IEnumerable<string> ShowTables(string dbName)
        {
            string sql = $"USE {dbName};SHOW TABLES;";
            IEnumerable<string> result = new List<string>();

            if (curDbConnection != null)
            {
                using (curDbConnection)
                {
                    if (curDbConnection.State != ConnectionState.Open)
                        curDbConnection.Open();

                    result = curDbConnection.Query<string>(sql);

                    curDbConnection.Close();
                }
            }
            return result;
        }

        public IEnumerable<object> ShowColumns(string dbName, string tableName)
        {
            string sql = $"USE {dbName};SHOW COLUMNS FROM {tableName};";
            IEnumerable<MySQLColumnMeta> result = new List<MySQLColumnMeta>();

            if (curDbConnection != null)
            {
                using (curDbConnection)
                {
                    if (curDbConnection.State != ConnectionState.Open)
                        curDbConnection.Open();

                    result = curDbConnection.Query<MySQLColumnMeta>(sql);

                    curDbConnection.Close();
                }
            }
            return result;
        }
    }
}
